<template>
  <el-form
    :model="formData"
    ref="formRef"
    @submit.prevent
    :rules="formRules"
    label-width="100px"
  >
    <el-row>
      <el-col>
        <el-form-item label="合同名称" prop="contractName">
          <el-input v-model.trim="formData.contractName"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-form-item label="合同编号" prop="contractNum">
          <el-input v-model.trim="formData.contractNum"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-form-item label="上传文档" prop="contractAttachmentArr">
          <el-upload
            name="uploadFile"
            multiple
            :accept="acceptTypes"
            :action="uploadComUrl"
            :headers="uploadHeaders"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :on-error="handleError"
            :file-list="defaultFileList"
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePreview"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg等格式文件,文件大小不得大于10M。
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <el-row justify="end">
    <el-button>取 消</el-button>
    <el-button type="primary" @click="handleSubmit">确 定</el-button>
  </el-row>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { cloneDeep } from "lodash-es";
import { useRoute } from "vue-router";
import { postContractAdd } from "/@/api/contract";
import NotifMessage from "/@/utils/message/notification";
import { useUpload } from "/@/hooks";

const {
  handleError,
  beforeAvatarUpload,
  uploadComUrl,
  acceptTypes,
  uploadHeaders
} = useUpload();

const emit = defineEmits(["emitSubmit"]);

const route = useRoute();

const formRef = ref<HTMLFormElement | null>(null) as any;
const handlePreview = (item: any) => {
  window.open(
    `${location.origin}${location.pathname}#/online?uuidFile=${item?.response.data.uuidFile}&fileName=${item?.response.data.fileName}`
  );
};
let formData = reactive({
  contractName: "",
  contractNum: "",
  contractAttachmentArr: []
});

const formRules = ref({
  contractName: [
    { required: true, message: "请输入合同名称", trigger: "change" }
  ],
  contractNum: [
    { required: true, message: "请输入合同编号", trigger: "change" }
  ],
  contractAttachmentArr: [
    { required: true, message: "请上传附件", trigger: "change" }
  ]
});

/* 上传 -- start */

let defaultFileList = ref([]);

const handleRemove = (file, fileList) => {
  defaultFileList.value = fileList;
  formData.contractAttachmentArr = formData.contractAttachmentArr.filter(
    item => {
      const uuid = file.response ? file.response.data.uuidFile : file.uuidFile;
      return item.uuidFile !== uuid;
    }
  );
};

const handleSuccess = (res, file, fileList) => {
  if (res.code === 200) {
    defaultFileList.value = fileList;
    formData.contractAttachmentArr.push(res.data);
  }
  formRef.value.clearValidate();
};

/* 上传 -- end */

const handleSubmit = async (): Promise<any> => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) return;
  try {
    const copyFormData = cloneDeep(formData);
    copyFormData.projectManageId = route.query?.id ?? "";
    const { code, message } = await postContractAdd(copyFormData);
    if (code === 200) {
      NotifMessage.success(message);
      emit("emitSubmit");
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};
</script>

<style lang="scss" scoped></style>
